﻿using Autofac;
using Autofac.Integration.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ZSZ.CommonMVC;
using ZSZ.AdminWeb.App_Start;
using ZSZ.IService;
using Quartz;
using Quartz.Impl;
using ZSZ.AdminWeb.Jobs;
using Quartz.Spi;

namespace ZSZ.AdminWeb
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            ModelBinders.Binders.Add(typeof(string), new TrimToDBCModelBinder());

            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();// 把当前的 程序集中的 Controller 都注册
                                                                                               // 不要忘了.PropertiesAutowired()
                                                                                               //  获取所有相关类库的程序集
            Assembly[] assemblies = new Assembly[] { Assembly.Load("ZSZ.Service") };
            builder.RegisterAssemblyTypes(assemblies)
            .Where(type => !type.IsAbstract && typeof(IServiceSupport).IsAssignableFrom(type))
            .AsImplementedInterfaces().PropertiesAutowired();
            var container = builder.Build();
            // 注册系统级别的 DependencyResolver ，这样当 MVC  框架创建 Controller  等对象的时候都管 Autofac 要对象。
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//!!!
            
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //GlobalFilters.Filters.Add(new ZSZExceptionFilter());
            //GlobalFilters.Filters.Add(new JsonNetActionFilter());
            //GlobalFilters.Filters.Add(new ZSZAuthorizeFilter());
            FilterConfig.RegisterFilters(GlobalFilters.Filters);

        }

        private void startQuartz()
        {
            IScheduler sched = new StdSchedulerFactory().GetScheduler();

            //给老板的报表开始
            JobDetailImpl jdBossReport
                = new JobDetailImpl("jdBossReport", typeof(BossReportJob));
            IMutableTrigger triggerBossReport
                = CronScheduleBuilder.DailyAtHourAndMinute(14, 47).Build();//每天23:45执行一次
            triggerBossReport.Key = new TriggerKey("triggerBossReport");
            sched.ScheduleJob(jdBossReport, triggerBossReport);
            //给老板的报表结束


            sched.Start();
        }
    }
}
